from io import BytesIO

from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect

from utils.image_code import check_code
from web import models
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSmsForm, LoginForm

"""
用户账户相关试图：注册、短信、登录、注销
"""


def register(request):
    """注册"""
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'web/register.html', {'form': form})

    form = RegisterModelForm(data=request.POST)

    if form.is_valid():
        # 验证通过，写入数据库 (密码要密文)
        instance = form.save()
        return JsonResponse({'status': True, 'data': 'web/login/'})

    return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):
    """发送短信"""
    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():  # 校验手机号不能为空并格式正确
        return JsonResponse({'status': True})

    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    """短信登录"""
    if request.method == 'GET':
        form = LoginSmsForm()
        return render(request, 'web/login_sms.html', {'form': form})

    form = LoginSmsForm(request.POST)
    if form.is_valid():
        # 登录成功
        mobile_phone = form.cleaned_data['mobile_phone']

        user_object = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()

        request.session['user_id'] = user_object.id
        request.session['user_name'] = user_object.username

        return JsonResponse({'status': True, 'data': '/web/index/'})

    return JsonResponse({'status': False, 'errors': form.errors})


def login(request):
    """用户名和密码登录"""
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'web/login.html', {'form': form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        pass_word = form.cleaned_data['pass_word']

        # (手机=username and pass_word=pass_word) or (邮箱=username and pass_word=pass_word)
        user_object = models.UserInfo.objects.filter(
            Q(email=username) | Q(mobile_phone=username)).filter(
            pass_word=pass_word).first()

        if user_object:
            # 登录成功，保存 2 周
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60 * 60 * 24 * 14)

            return redirect('web:index')
        form.add_error('username', '用户名或密码错误')

    return render(request, 'web/login.html', {'form': form})


def image_code(request):
    """生成图片验证码"""
    image_object, code = check_code()

    # 存储 session 并设置过期时间
    request.session['image_code'] = code
    request.session.set_expiry(60)

    stream = BytesIO()
    image_object.save(stream, 'png')

    return HttpResponse(stream.getvalue())


def logout(request):
    request.session.flush()
    return redirect('web:index')
